package com.newcapec.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.*;
import java.util.Properties;

public class JDBCUtil {
    //定义url user password
    /*private static final String URL = "jdbc:mysql://localhost:3306/news?useSSL=false&useUnicode=true&characterEncoding=utf8";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";*/
    private static DataSource dataSource;
    private static final Properties properties;
    /*
    * 加载驱动器只加载一次
    * */
    static {
        properties = new Properties();
        try {
            properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties"));
            //Class.forName(properties.getProperty("mysqlDriver"));
            //使用德鲁伊创建一个线程池
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*
    * 获取Connection连接的方法
    * */
    public static Connection getConn() {
        try {
            //return DriverManager.getConnection(properties.getProperty("mysqlUrl"),properties.getProperty("mysqlUserName"),properties.getProperty("mysqlPassword"));
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    /*
    * 关闭资源的方法
    * */
    public static void closeSource(Connection conn, Statement stmt, ResultSet rs){
        try {
            if (rs != null){
                rs.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (stmt != null){
                stmt.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (conn != null){
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
